/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

#include <iostream>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
void traversal(TreeNode* cur, vector<int> &vec){
        if (cur == nullptr){
            return;
        }

        traversal(cur->left, vec);
        traversal(cur->right, vec);
        vec.push_back(cur->val);
    }

    vector<int> postorderTraversal(TreeNode* root) {
        // 1.递归法
        // TreeNode * cur = root;
        // vector<int> vec;
        // traversal(cur, vec);
        
        // 2.迭代法
        vector<int> vec;
        stack<TreeNode *> st;
        st.push(root);

        while (!st.empty()){
            TreeNode * node = st.top();
            st.pop();
            if(node != nullptr){
                vec.push_back(node->val);
                st.push(node->left);
                st.push(node->right);
            } 
        }
        reverse(vec.begin(), vec.end());

        return vec;
    }
};